package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.exception.BusiException;
import com.ruoyi.system.domain.ZfbConfig;
import com.ruoyi.system.mapper.ZfbConfigMapper;
import com.ruoyi.system.service.BaseServiceImpl;
import com.ruoyi.system.service.ZfbConfigService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ZfbConfigServiceImpl extends BaseServiceImpl<ZfbConfigMapper, ZfbConfig> implements ZfbConfigService {


    @Override
    public ZfbConfig getConfig() {
        ZfbConfig zfbConfig = new ZfbConfig();
        zfbConfig.setStatus(1);
        PageDomain pageDomain = new PageDomain();

        List<ZfbConfig> list = this.findList(zfbConfig, pageDomain);
        if (CollectionUtil.isEmpty(list)) {
            throw new BusiException("没有支付宝收款");
        }
        zfbConfig = list.get(RandomUtil.randomInt(list.size()));

        return this.getById(zfbConfig.getId());
    }

    @Override
    public ZfbConfig getChannelConfig(String channelCode) {
        ZfbConfig zfbConfig = new ZfbConfig();
        zfbConfig.setStatus(1);
        zfbConfig.setChannelCode(channelCode);
        PageDomain pageDomain = new PageDomain();

        List<ZfbConfig> list = this.findList(zfbConfig, pageDomain);
        if (CollectionUtil.isEmpty(list)) {
            throw new BusiException("通道暂不可用");
        }
        zfbConfig = list.get(RandomUtil.randomInt(list.size()));

        return this.getById(zfbConfig.getId());
    }

    @Override
    protected void setQuery(QueryWrapper<ZfbConfig> query) {
        query.select(ZfbConfig.class, info -> !(info.getColumn().equals("private_key")
                || info.getColumn().equals("alipay_public_key")));


    }
}
